import logging.handlers
import os
# 项目根路径l
import time

currentFile = os.path.abspath(__file__)
currentPath = os.path.dirname(currentFile)
FatherPath = os.path.dirname(currentPath)

if not os.path.exists(os.path.join(FatherPath, 'logs')):
    os.makedirs(os.path.join(FatherPath, 'logs'))
today = time.strftime('%Y%m%d', time.localtime(time.time()))

# 日志配置
LOGGING_CONFIG = {
    "name": "System",
    "filename": os.path.join(FatherPath, 'logs', F'{today}.log'),
    "err_filename": os.path.join(FatherPath, 'logs', F'{today}-error.log'),
    "encoding": "utf-8",
    "fomater": '%(asctime)s %(filename)s[line:%(lineno)s] %(levelname)s: %(message)s', "level": "DEBUG",
    "maxBytes": 1024 * 1024 * 50,
    "backupCount": 10
}


def logger():
    name = LOGGING_CONFIG['name']
    filename = LOGGING_CONFIG['filename']
    err_filename = LOGGING_CONFIG['err_filename']
    encoding = LOGGING_CONFIG['encoding']
    fomater = LOGGING_CONFIG['fomater']
    level = LOGGING_CONFIG['level']
    maxBytes = LOGGING_CONFIG['maxBytes']
    backupCount = LOGGING_CONFIG['backupCount']

    logger = logging.getLogger(name)
    logger.setLevel(level)
    fmt = logging.Formatter(fomater)
    console_handle = logging.StreamHandler()
    console_handle.setLevel("INFO")
    console_handle.setFormatter(fmt)
    logger.addHandler(console_handle)

    file_handle = logging.handlers.RotatingFileHandler(filename,
                                                       maxBytes=maxBytes,
                                                       backupCount=backupCount, encoding=encoding)
    file_handle.setLevel(level)
    file_handle.setFormatter(fmt)
    logger.addHandler(file_handle)
    err_file_handle = logging.handlers.RotatingFileHandler(err_filename,
                                                           maxBytes=maxBytes,
                                                           backupCount=backupCount,
                                                           encoding=encoding)
    err_file_handle.setLevel('ERROR')
    err_file_handle.setFormatter(fmt)
    logger.addHandler(err_file_handle)
    return logger


if __name__ == '__main__':
    log = logger()
    log.error("这是一个测试123123")
    log.info("这是一个测试3123123")
